﻿@inject IPeopleService faceService
@inject ILogger<PeopleGrid> logger
@inject IJSRuntime JsRuntime
@inherits ImageGridBase

<div class="imagegrid" id="scroll-area">
    @if( people.Any() )
    {
        @foreach( var person in people )
        {
            <PersonTile Person="person" PersonChanged="@RefreshData" Small="@Small" 
                        Disabled="@Disabled" OnPersonClicked="PersonClicked"/>
        }

        if ( !endOfImages )
        {
            <div class="damselfly-moreimages" id="list-end">
                <ProgressSpinner ProgressText="Loading people..."/>
            </div>
        }
        else
        {
            <div id="snackbar" class="@toastClass">No more images to show.</div>
        }
    }
    else
    {
        @if( ShowNotFoundMessage )
        {
            <div class="damselfly-searchmsg">
                No people were found.
            </div>
        }
    }
</div>

@code {
    [Parameter] public string? SearchText { get; set; }

    [Parameter] public Person.PersonState? PersonState { get; set; }
    
    [Parameter] public bool Small { get; set; }
    
    [Parameter] public EventCallback<Person> OnPersonClicked { get; set; }
    
    [Parameter] public bool Disabled { get; set; }
    
    [Parameter] public int? ExcludeSelectedPersonId { get; set;  }

    [Parameter] public bool ShowNotFoundMessage { get; set; } = true;

    const int peoplePerPage = 30;
    private bool NoImagesSelected => !selectionService.Selection.Any();
    bool endOfImages = false;
    string toastClass = string.Empty;

    private List<Person> people  = new();

    public string ResultsMessage { get; set; }

    private async Task PersonClicked( Person person )
    {
        await OnPersonClicked.InvokeAsync(person);
    }
    
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if ( firstRender )
        {
            await JsRuntime.InvokeVoidAsync("InfiniteScroll.Init", "scroll-area", "list-end", DotNetObjectReference.Create(this));
        }
    }

    protected override async Task OnParametersSetAsync()
    {
        await RefreshData();
        await base.OnParametersSetAsync();
    }

    private async Task RefreshData()
    {
        await LoadData(true);
    }

    [JSInvokable]
    // Debugging assistant to help us differentiate between JS calls and other data loads
    public async Task LoadMoreData()
    {
        logger.LogTrace("Javscript callback triggered to load more data.");

        await LoadData();
    }

    private async Task LoadData(bool refresh = false)
    {
        var req = new PeopleRequest
        {
            SearchText = SearchText,
            State = PersonState,
            Start = refresh ? 0 : people.Count(),
            Count = peoplePerPage
        };

        var newPeople = await faceService.GetPeople(req);
        
        if( ExcludeSelectedPersonId != null )
            newPeople = newPeople.Where( x => x.PersonId != ExcludeSelectedPersonId.Value).ToList();
        
        endOfImages = newPeople.Count < peoplePerPage;
        if( refresh )
            people.Clear();
        people.AddRange( newPeople);
        StateHasChanged();
    }

}